<script setup>
import {nextTick, onMounted, reactive, ref} from "vue";
import Table from '@/components/admin/Table.vue'
import Dialog from '@/components/admin/EditDialog.vue'
import inlineDialog from '@/components/admin/inlineDialog.vue';
import {Delete, Download, Plus, ZoomIn, Search} from '@element-plus/icons-vue'
import {
  GetSellPetMessageService,
  addSellPetService,
  deleteSellNoticeUrlService,
  deleteSellNoticeUrlsService,
  editSellMessageService
} from '@/api/sellpetmessage.js'
import {ElMessage} from "element-plus";
// 搜索查询
const columns = [
  {
    name: 'sell_id',
    label: '编号',
    search: true,
    valueType: 'input',
    span: 8,
    attrs: {
      placeholder: '请输入',
    },
  },
  {
    name: 'species',
    label: '种类',
    search: true,
    valueType: 'input',
    span: 8,
    attrs: {
      placeholder: '请输入',
    },
  },
  {
    name: 'sex',
    label: '性别',
    slot: true,
    search: true,
    span: 8,
    attrs: {
      placeholder: '请输入',
    },
    options: [
      {
        value: 1,
        label: '雄性',
      },
      {
        value: 0,
        label: '雌性',
      },
    ],
    valueType: 'select',
  },
  {
    name: 'price',
    label: '价格',
    search: true,
    sortable: true,
    valueType: 'input',
    span: 8,
    attrs: {
      placeholder: '请输入',
    },
  },

  {
    name: 'create_time',
    label: '日期',
    sorter: true,
    search: true,
    valueType: 'date-picker',
    span: 8,

  },
]
let baseColumns = reactive(columns)

// 表格相关参数
const sellMsg = ref({
  columns: [
    {
      label: '宠物编号',
      prop: 'sell_id',
      width: '130',
    },
    {
      label: '宠物花名',
      prop: 'sell_name',
      width: '130',
    },
    {
      label: '种类',
      prop: 'catagory',
      width: '120',
      formatter: (row) => {
        switch (row.catagory) {
          case '狗': {
            return '狗'
          }
          case '猫': {
            return '猫'
          }
        }
      }
    },
    {
      label: '品种',
      prop: 'species',
      width: '130',
    },
    {
      label: '年龄',
      prop: 'age',
      width: '100',
    },
    {
      label: '性别',
      prop: 'sex',
      width: '120',
      formatter: (row) => {
        switch (row.sex) {
          case '1': {
            return '雄性'
          }
          case '2': {
            return '雌性'
          }
        }
      }
    },
    {
      label: '图片',
      prop: 'picture',
      width: '250',
      type: 'pic',
    },
    {
      label: '数量',
      prop: 'quantity',
      width: '100'
    },
    {
      label: '价格',
      prop: 'price',
      width: '150',
      formatter: (row) => {
        return row.price + '元'
      }
    },
    {
      label: '最新上架时间',
      prop: 'create_time',
      width: '200'
    },
    {
      label: '状态',
      prop: 'status',
      width: '150',
      type: 'tag',
      formatter: (row) => {
        switch (row.status) {
          case '1': {
            return '未上架'
          }
          case '2': {
            return '上架在售'
          }
          case '3': {
            return '下架已售'
          }
        }
      }
    },
    {
      label: '详细描述',
      prop: 'description',
      width: '200'
    }
  ],
  data: [],
  loading: true
})
// 展示数据
const getList = (keyword) => {
  GetSellPetMessageService(all.page, all.limit, keyword)
      .then((res) => {
        sellMsg.value.data = res.data.results.data
        // 获取数据总数
        all.total = res.data.count
        sellMsg.value.loading = false
        // console.log(res.data.results.data)
      })
      .catch((err) => {
        console.log(err)
      })
}
onMounted(() => {
  getList()
})
// 分页
const all = reactive({
  // 总数
  total: 0,
  // 页
  page: 1,
  // 条
  limit: 10,
})
const sizeChange = (val) => {
  all.limit = val;
  getList()
};
/**
 * 页
 * val -- 当前条
 */
const currentChange = (val) => {
  all.page = val;
  getList()
};

// 查询
const onSubmit = (val) => {
  console.log(val)
  sellMsg.value.loading = true
  setTimeout(() => {
    getList(val)
  }, 1000)
}

// 对话框展开
const dialogObject = reactive({
  dialogVisible: false,
  title: '',
  width: '700',
  successBtnText: '确定',
  closeBtnText: '取消',
  isFooter: true
})

// 上架对话框
const addClick = () => {

  dialogObject.dialogVisible = true
  console.log(dialogObject.dialogVisible)
  dialogObject.title = '建档'
}
// 对话框数据绑定
const form = ref({
  sell_id: '',
  sell_name: '',
  catagory: '',
  species: '',
  age: '',
  sex: '',
  picture: '',
  quantity: '',
  price: '',
  create_time: '',
  status: '',
  description: ''
})

// 对话框
const formfields = ref({
  base: [
    {
      label: '宠物花名', field: 'sell_name',
      rules: [
        {required: true, message: '宠物花名需要填写', trigger: 'blur'}
      ]
    },
    {
      label: '种类', field: 'catagory',type:'select',
      options: {
        data: [{label: '狗', value: '狗'}, {label: '猫', value: '猫'}]
      },
      rules: [
        {required: true, message: '请选择宠物的种类', trigger: 'blur'},
      ]
    },
    {
      label: '品种', field: 'species',
      rules: [
        {required: true, message: '请填写品种', trigger: 'blur'}
      ]
    },
    {
      label: '年龄', field: 'age',
      rules: [
        {required: true, message: '请填写一下宠物年龄', trigger: 'blur'},
      ]
    },
    {
      label: '性别', field: 'sex', type: 'select',
      options: {
        data: [{label: '雄性', value: '1'}, {label: '雌性', value: '2'}]
      },
      rules: [
        {required: true, message: '年龄需要填写', trigger: 'blur'},
      ]
    },
    {
      label: '上传图片', field: 'picture', type: 'pic'
    },
    {
      label: '数量', field: 'quantity',
      rules: [
        {required: true, message: '请填写数量', trigger: 'blur'}
      ]
    },
    {
      label: '价格', field: 'price',
      rules: [
        {required: true, message: '请根据宠物类型填写总价', trigger: 'blur'}
      ]
    },
    {
      label: '上架时间', field: 'create_time', type: 'alldate',
      rules: [{required: true, message: '选择上架时间'}]
    },
    {
      label: '状态', field: 'status', type: 'select',
      options: {
        data: [{label: '未上架', value: '1'}, {label: '在售', value: '2'}, {label: '已售', value: '3'}]
      },
      rules: [{required: true, message: '选择目前的商品状态'}]
    },
    {
      label: '详细描述', field: 'description'
    },
  ],
})

// 图片上传的token
const uploadHeaders = ref({
  Authorization: 'bearer' + ' ' + localStorage.getItem('admin_token')
})

// 上传前的图片校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpg" && rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    console.log(rawFile)
    ElMessage.error('文件格式必须是jpg、jpeg或者png')
    return false
  } else if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('该文件格式不能超过 20MB!')
    return false
  }
  return true
}

// 图片先上传回服务器然后再将图片本地的地址返回来，再走drf将图片存放本地的路径存到数据库
const handleAvatarSuccess = async (response, file) => {
  form.value.picture = response['0']
  console.log('图片的地址', form.value.picture)
}
// 生成随机订单号
const generateRandomSerialNumber = () => {
  const timePart = Date.now().toString(36).slice(-4); // 使用当前时间的后4位作为一部分
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  let letterPart = '';

  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    letterPart += characters.charAt(randomIndex);
  }
  return timePart + letterPart;
}
// 提交表单增加数据
const handleFormSubmit = async (form) => {
  console.log(generateRandomSerialNumber())
  form.sell_id = generateRandomSerialNumber()
  form.age = parseInt(form.age, 10)
  form.price = parseFloat(form.price)
  await addSellPetService(form)
      .then((res) => {
        // console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}
// 绑定表格的内容(选项selection)
const multipleTableRef = ref()
// 单个删除组件
const handleDelete = (row) => {
  const params = row.id;
  console.log(params)
  deleteSellNoticeUrlService(params).then((res) => {
    console.log(res.data);
    getList()
  });
}
// 批量选择并删除
const multipleSelection = ref([]);
const selectionchange = (val) => {
  multipleSelection.value = val
  console.log(multipleSelection.value)
}
// 批量选择并删除
const handleDeleteArray = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.warning('麻烦你选中了再点')
  }
  for (var i = 0; i < multipleSelection.value.length; i++) {
    const params = multipleSelection.value[i].id;
    const Ids = []
    Ids.push(...multipleSelection.value.map(row => row.id))
    console.log(Ids);
    deleteSellNoticeUrlsService({Ids: Ids})
        .then((res) => {
          multipleSelection.value = []
          console.log(res.data);
          getList()
        });
  }
}
// 单个数据的编辑
const handleEdit = (index, row) => {
  dialogObject.dialogVisible = true
  dialogObject.title = '调整业务'
  // console.log(row)
  nextTick(() => {
    form.value.sell_id = row.sell_id
    form.value.sell_name = row.sell_name
    form.value.catagory = row.catagory
    form.value.species = row.species
    form.value.age = row.age
    form.value.sex = row.sex
    form.value.picture = row.picture
    form.value.quantity = row.quantity
    form.value.price = row.price
    form.value.create_time = row.create_time
    form.value.status = row.status
    form.value.description = row.description
    form.value.id = row.id
  })
  console.log(form)
}
// 编辑表单提交
const handleFormEdit = async (form) => {
  console.log('form', form)
  await editSellMessageService(form)
      .then((res) => {
        console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}
</script>
<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <inlineDialog @submit="onSubmit" :columns="baseColumns"/>
      </div>
    </template>
    <div class="operbutton">
      <el-button type="success" @click="addClick">上架</el-button>
      <el-button type="danger" @click="handleDeleteArray">批量删除</el-button>
    </div>
    <Table
        ref="multipleTableRef"
        :customdata="sellMsg"
        :all="all"
        @handleSizeChange="sizeChange"
        @handleCurrentChange="currentChange"
        @handleSelectionChange="selectionchange"
    >
      <template #status="{row}">
        <el-tag v-if="row.status === '1'" size="large" type="info">未上架</el-tag>
        <el-tag v-if="row.status === '2'" size="large" type="success">在售</el-tag>
        <el-tag v-if="row.status === '3'" size="large" type="danger">已售</el-tag>
      </template>
      <template #picture="{row}">
        <div>
          <el-image
              fit="cover"
              :src="row.picture"
              :preview-src-list="[row.picture]"
              style="width: 120px; height: 120px"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              preview-teleported="true"
          />
        </div>
      </template>
      <template #operate>
        <el-table-column label="操作" fixed="right" width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-popconfirm title="是否确定要删除吗" confirm-button-text="是" cancel-button-text="否"
                           @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button
                    size="small"
                    type="danger"
                >删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </template>
    </Table>
    <Dialog
        :dialogobject="dialogObject"
        :formlist="formfields.base"
        :model="form"
        @submit="handleFormSubmit"
        @edit="handleFormEdit"
    >
      <template #pictures="{row}">
        <el-upload
            action="http://127.0.0.1:8000/admincharge/sellmsg/uploadmessage/"
            list-type="picture-card"
            :auto-upload="true"
            ref="pictureUpload"
            :headers="uploadHeaders"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :limit="3"

        >
          <el-icon>
            <Plus/>
          </el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
              <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in/></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><Delete/></el-icon>
          </span>
        </span>
            </div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="form.fileList" alt="Preview Image"/>
        </el-dialog>
      </template>
    </Dialog>

  </el-card>
</template>

<style scoped>

.operbutton {
  margin-bottom: 30px;
}
</style>